﻿using Abp.Application.Services.Dto;
using Abp.UI;
using Abp.Web.Models;
using Abp.Web.Mvc.Authorization;
using Abp.Web.Mvc.Controllers;
using Abp.Web.Mvc.Models;
using MyABP.Authorization.Users;
using MyABP.Tasks;
using MyABP.Tasks.Dtos;
using MyABP.Users;
using MyABP.Users.Dto;
using MyABP.Web.Models.Tasks;
using MyABP.Web.Models.Users;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using X.PagedList;

namespace MyABP.Web.Controllers
{
    [AbpMvcAuthorize]
    public class TasksController : AbpController
    {
        private readonly ITaskAppService _taskAppService;
        private readonly IUserAppService _userAppService;
        private readonly IErrorInfoBuilder _errorInfoBuilder;
        public TasksController(ITaskAppService taskAppService, IUserAppService userAppService, IErrorInfoBuilder errorInfoBuilder)
        {
            _taskAppService = taskAppService;
            _userAppService = userAppService;
            _errorInfoBuilder = errorInfoBuilder;
        }

        public ActionResult Index(GetTasksInput input)
        {
            var output = _taskAppService.GetTasks(input);
            var per = _taskAppService.GetPermissions();
            var model = new IndexViewModel(output.Tasks)
            {
                SelectedTaskState = input.State

            };
            return View(model);
        }

        public PartialViewResult GetList(GetTasksInput input)
        {
            var output = _taskAppService.GetTasks(input);
            return PartialView("_List",output.Tasks);
        }


        [ChildActionOnly]
        public PartialViewResult Create()
        {
            
                //var userList = _userAppService.GetUsers();
                //ViewBag.AssignedPersonId = new SelectList(userList.Items, "Id", "Name");

                var users = _userAppService.GetUsers();

                var userList = users.Select(t => new SelectListItem()
                {
                    Text = t.Surname + t.Name,
                    Value = t.Id.ToString()
                }).ToList();

                //List<SelectListItem> lists = userList as List<SelectListItem>;
                ViewBag.AssignedPersonId = userList;

                return PartialView("_CreateTask");
           
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(CreateTaskInput task)
        {
            try
            {
                var id = _taskAppService.CreateTask(task);

                var input = new GetTasksInput();
                var output = _taskAppService.GetTasks(input);

                //return PartialView("_List", output.Tasks);
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
               
                return View(
               "Error",
               new ErrorViewModel(
                   _errorInfoBuilder.BuildForException(ex),
                   ex
               )
           );
            }
        }
        public PartialViewResult Edit(int id)
        {
            var task = _taskAppService.GetTaskById(id);

            var updateTaskDto = AutoMapper.Mapper.Map<UpdateTaskInput>(task);

            var users = _userAppService.GetUsers();
            var userList = users.Select(t => new SelectListItem()
            {
                Text = t.Surname + t.Name,
                Value = t.Id.ToString()
            }).ToList();

            //List<SelectListItem> lists = userList as List<SelectListItem>;
            ViewBag.AssignedPersonId = userList;

            return PartialView("_EditTask", updateTaskDto);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(UpdateTaskInput updateTaskDto)
        {
            _taskAppService.UpdateTask(updateTaskDto);

            //var input = new GetTasksInput();
            //var output = _taskAppService.GetTasks(input);

            //return PartialView("_List", output.Tasks);
            return RedirectToAction("Index");
        }

        public ActionResult PagedList(int? page)
        {
            //每页行数
            var pageSize = 3;
            var pageNumber = page ?? 1;//第几页

            var filter = new GetTasksInput
            {
                SkipCount = (pageNumber - 1) * pageSize,//忽略个数
                MaxResultCount = pageSize
            };
            var result = _taskAppService.GetPagedTasks(filter);

            //已经在应用服务层手动完成了分页逻辑，所以需手动构造分页结果
            var onePageOfTasks = new StaticPagedList<TaskDto>(result.Items, pageNumber, pageSize, result.TotalCount);
            //将分页结果放入ViewBag供View使用
            ViewBag.OnePageOfTasks = onePageOfTasks;

            return View();
        }

        ///// <summary>
        ///// 获取创建任务分部视图
        ///// 该方法使用ICacheManager进行缓存，在WebModule中配置缓存过期时间为10mins
        ///// </summary>
        ///// <returns></returns>
        //public PartialViewResult RemoteCreate()
        //{
        //    //1.1 注释该段代码，使用下面缓存的方式
        //    //var userList = _userAppService.GetUsers();

        //    //1.2 同步调用异步解决方案（最新Abp创建的模板项目已经去掉该同步方法，所以可以通过下面这种方式获取用户列表）
        //    //var userList = AsyncHelper.RunSync(() => _userAppService.GetUsersAsync());

        //    //1.3 缓存版本
        //    var userList = _cacheManager.GetCache("ControllerCache").Get("AllUsers", () => _userAppService.GetUsers());

        //    //1.4 转换为泛型版本
        //    //var userList = _cacheManager.GetCache("ControllerCache").AsTyped<string, ListResultDto<UserListDto>>().Get("AllUsers", () => _userAppService.GetUsers());

        //    //1.5 泛型缓存版本
        //    //var userList = _cacheManager.GetCache<string, ListResultDto<UserListDto>>("ControllerCache").Get("AllUsers", () => _userAppService.GetUsers());

        //    ViewBag.AssignedPersonId = new SelectList(userList.Items, "Id", "Name");
        //    return PartialView("_CreateTaskPartial");
        //}









    }
}